package com.zhq.okhttp.subscribe;


import com.alibaba.fastjson.JSON;
import com.zhq.constant.AppConstant;
import com.zhq.okhttp.RxApiManager;
import com.zhq.okhttp.bean.HttpBeanResponse;

import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.ResponseBody;
import retrofit2.HttpException;


/**
 * Created by Administrator on 2017/8/8.
 * <p>
 * 订阅Ui主线程
 */
public class SubscriberUIThread implements Observer<ResponseBody> {
    private HttpRequestListener listener;
    private Disposable disposable;

    public SubscriberUIThread(HttpRequestListener listener) {
        this.listener = listener;
        RxApiManager.get().add(listener);
    }


    @Override
    public void onError(Throwable e) {
        if (listener != null) {
            String msg = e.getLocalizedMessage();
            if (e instanceof SocketTimeoutException) {
                msg = "连接网络超时，请检查您的网络状态";
            } else if (e instanceof ConnectException) {
                msg = "与服务端连接失败，请检查您的网络状态";
            } else if (e instanceof HttpException) {
                msg = e.getMessage();
                if (e instanceof HttpException) {
                    HttpException httpException = (HttpException) e;
                    int code = httpException.code();
                    msg = httpException.getMessage();
                    if (code ==  AppConstant.HttpResponse.NETWORK_CONNECT_TIME_OUT) {
                        msg = "网络不给力";
                    }
                }
            }
            removeDisposable();
            listener.requestFailure(msg);
        }
    }

    @Override
    public void onComplete() {
        removeDisposable();
    }

    @Override
    public void onSubscribe(Disposable d) {
        disposable = d;
    }

    @Override
    public void onNext(ResponseBody response) {
        if (listener != null) {
            try {
                String data = response.string();
                HttpBeanResponse beanResponse = JSON.parseObject(data, HttpBeanResponse.class);
                if (beanResponse.getStatusCode() == AppConstant.HttpResponse.SUCCESS) {
                    listener.requestSuccess(beanResponse.getData());
                } else {
                    listener.requestErrorType(beanResponse.getMessage(), beanResponse.getStatusCode());
                }
            } catch (IOException e) {//解析异常以及IO异常
                listener.requestErrorType("数据出错", AppConstant.HttpResponse.DATA_PARSE_ERROR);
            }
        } else {
            removeDisposable();
        }

    }

    /**
     * 销毁disposable
     */
    private void removeDisposable() {
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
            disposable = null;
        }
    }


}
